package com.common.basic.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class ComboBoxPopulator {

	public static List<ComboValue> populate(List<?> dataList,
			String valueFieldString, String labelFieldName) {
		if (dataList == null || dataList.size() == 0
				|| valueFieldString == null
				|| valueFieldString.trim().length() == 0
				|| labelFieldName == null
				|| labelFieldName.trim().length() == 0)
			return null;

		List<ComboValue> result = new ArrayList<ComboValue>();
		ComboValue comboValue;
		for (Object obj : dataList) {
			comboValue = new ComboValue();
			comboValue.setStValue(ComboBoxPopulator.invoke(obj,
					valueFieldString));
			comboValue
					.setStLabel(ComboBoxPopulator.invoke(obj, labelFieldName));

			result.add(comboValue);
		}

		return result;
	}

	public static List<ComboValue> populate(List<?> dataList,
			String valueFieldString, String[] arrayLabelFieldName,
			String delimiter) {
		if (dataList == null || dataList.size() == 0
				|| valueFieldString == null
				|| valueFieldString.trim().length() == 0
				|| arrayLabelFieldName == null
				|| arrayLabelFieldName.length == 0 || delimiter == null
				|| delimiter.trim().length() == 0)
			return null;

		List<ComboValue> result = new ArrayList<ComboValue>();
		ComboValue comboValue;
		StringBuffer sb;
		for (Object obj : dataList) {
			comboValue = new ComboValue();
			comboValue.setStValue(ComboBoxPopulator.invoke(obj,
					valueFieldString));
			sb = new StringBuffer("");
			int i = 0;
			for (String string : arrayLabelFieldName) {
				sb.append(ComboBoxPopulator.invoke(obj, string));
				i++;
				if (i < arrayLabelFieldName.length)
					sb.append(" " + delimiter + " ");
			}
			comboValue.setStLabel(sb.toString());

			result.add(comboValue);
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	private static String invoke(Object obj, String fieldName) {
		if (obj != null && fieldName != null && !"".equals(fieldName)) {
			try {
				Class clazz = obj.getClass();
				Map<String, Field> mapField = new HashMap<String, Field>();

				Field[] fields = clazz.getDeclaredFields();
				mapField.clear();
				for (int i = 0; i < fields.length; ++i)
					mapField.put(fields[i].getName(), fields[i]);

				if (!clazz.equals(obj.getClass())
						|| !mapField.containsKey(fieldName))
					return null;

				Field field = mapField.get(fieldName);
				field.setAccessible(true);
				return String.valueOf(field.get(obj));
			} catch (Exception ex) {
			}
		}
		return null;
	}
}
